// 定义共享状态的类型
export interface SharedState {
  user: any;
  theme: string;
  [key: string]: any;
}

const STORAGE_PREFIX = 'qiankun_demo_';

// 存储工具类
export class StorageUtil {
  private static instance: StorageUtil;
  private actions: any;

  private constructor() {}

  static getInstance(): StorageUtil {
    if (!StorageUtil.instance) {
      StorageUtil.instance = new StorageUtil();
    }
    return StorageUtil.instance;
  }

  // 初始化 actions
  setActions(actions: any) {
    this.actions = actions;
  }

  // 设置数据
  setItem(key: string, value: any, isGlobal: boolean = false): void {
    const storageKey = `${STORAGE_PREFIX}${key}`;
    const data = JSON.stringify(value);
    localStorage.setItem(storageKey, data);
    
    if (isGlobal && this.actions) {
      this.actions.setGlobalState({ [key]: value });
    }
  }

  // 获取数据
  getItem<T>(key: string): T | null {
    const storageKey = `${STORAGE_PREFIX}${key}`;
    const data = localStorage.getItem(storageKey);
    return data ? JSON.parse(data) : null;
  }

  // 删除数据
  removeItem(key: string, isGlobal: boolean = false): void {
    const storageKey = `${STORAGE_PREFIX}${key}`;
    localStorage.removeItem(storageKey);
    
    if (isGlobal && this.actions) {
      this.actions.setGlobalState({ [key]: null });
    }
  }

  // 清除所有数据
  clear(): void {
    Object.keys(localStorage).forEach(key => {
      if (key.startsWith(STORAGE_PREFIX)) {
        localStorage.removeItem(key);
      }
    });
  }
}

export const storage = StorageUtil.getInstance();